package stack;

import java.util.Stack;

//                                               逆波兰表达式求值
public class Pratice3 {
    public int evalRPN(String[] tokens) {
        //1.先创建一个栈
        Stack<Integer> stack = new Stack<>();
        //2.遍历 tokens
        for (String token:tokens){
            //判断是否为数字,  是数字则入栈,
            if (isNumber(token)){
                stack.push(Integer.parseInt(token));
                continue;
            } else {
                //不是数字 就取出两个栈顶元素进行运算
                int num2 = stack.pop();
                int num1 = stack.pop();
                if (token.equals("+")){
                    stack.push(num1 + num2);
                }
                if (token.equals("-")){
                    stack.push(num1 - num2);
                }
                if (token.equals("*")){
                    stack.push(num1 * num2);
                }
                if (token.equals("/")){
                    stack.push(num1 / num2);
                }
            }
        }
        return stack.pop();
    }
    private boolean isNumber(String elem){
        if (elem.equals("+") || elem.equals("-") || elem.equals("*") || elem.equals("/")){
            return false;
        }
        return true;
    }
}
